<?php

namespace App\Applet\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Match;
use App\Models\MatchReport;

class IndexController extends Controller
{
    // 首页热门比赛
	public function hotMatches(Request $request)
    {
        $where = [];
        if ($request->type == 'single') {
            $where[] = ['sport_id', 1];
        } else if ($request->type == 'double') {
            $where[] = ['sport_id', 2];
        } else if ($request->type == 'hot') {
            $mids = array_unique(MatchReport::get()->pluck('match_id')->toArray());
            $where[] = [function ($q) use ($mids) {
                $q->whereIn('id', $mids);
            }];
        }

        $result = Match::with(['level', 'group', 'sport', 'reportPeople'])->where($where)->paginate()->toArray();
        $data = [];
        foreach ($result['data'] as $v) {
            
            $data[] = $this->filterData($v);
        }
        $result['data'] = $data;
        return $this->success($result);
    }

    // 活动详情
    public function matchesDetail(Request $request)
    {
        $result = Match::with(['level', 'group', 'sport', 'venue'])->find($request->matches_id);
        if (!$result) {
            return $this->error('该比赛不存在');
        }
        $data = $this->filterData($result->toArray());
        return $this->success($data);
    }


    // 过滤处理数据
    public function filterData($v = [])
    {
        $bt = strtotime($v['begin_time']);
        $report_count = isset($v['report_people']) ? count($v['report_people']) : 0;
        return [
            'id' => $v['id'],
            'name' => $v['name'] ?? '-',
            'limit' => $v['limit'] ?? 0,
            'report' => $report_count,
            'status' => '报名中',
            'sport' => $v['sport']['name'] ?? '-',
            'level' => $v['level']['name'] ?? '-',
            'group' => $v['group']['name'] ?? '-',
            'addr' => $v['addr'] ?? '-',
            'date' => date('Y-m-d', $bt),
            'month_day' => date('m-d', $bt),
            'time' => date('H:i', $bt),
            'week' => getWeek(date('w', $bt)),
            'money' => $v['money'],
            'venue' => $v['venue'] ?? [],
        ];
    }
}